package sample;

import javafx.application.Platform;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

/**
 * Created by Administrator on 2016/6/27.
 */
public class SocketServerManager extends Thread {
    private List<ConnectThread> connectThreads = new ArrayList<>();
    private OnReceiverListener onReceiveTextListener;

    @Override
    public void run() {
        super.run();
        ServerSocket serverSocket;
        try {
            serverSocket = new ServerSocket(9999);
            System.out.println("服务器已经建立，等待客户端接入，端口为：" + serverSocket.getLocalSocketAddress());
            while (true) {
                Socket mSocket = serverSocket.accept();
                if (mSocket != null) {
                    ConnectThread connectThread = new ConnectThread(mSocket);
                    connectThread.setOnReceiveTextListener(onReceiveTextListener);
                    connectThread.start();
                    connectThreads.add(connectThread);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void sendText(String text) {
        connectThreads.forEach(connectThread -> connectThread.sendText(text));
    }

    public void setOnReceiveTextListener(OnReceiverListener onReceiveTextListener) {
        this.onReceiveTextListener = onReceiveTextListener;
    }
}
